package com.soft.idc.common.control;

import java.util.Map;

import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.render.CaptchaRender;
import com.soft.idc.common.model.IdcOrg;
import com.soft.idc.common.model.IdcRole;
import com.soft.idc.common.model.IdcUser;
import com.soft.idc.common.service.IdcMenuService;

public class LoginController extends Controller {

	public void index() {
		//String orgid = this.getPara("orgid");
		String url = this.getRequest().getRequestURL().toString();
		String[] args = url.split("\\/");
		String endFix = args[args.length-1];
		String target = PropKit.get(endFix,"login_default.html");
		this.render("/login/"+target);
	}

	public void submit() {
		String username = this.getPara("username");
		String password = this.getPara("password");
		String imgCode = this.getPara("imgCode");

		boolean flag = CaptchaRender.validate(this, imgCode);
		if (flag != false) {
			IdcUser u = IdcUser.dao.findFirst("select * from idc_user u where u.username = ? ", username);
			IdcRole role = IdcRole.dao.findById(u.getRoleId());
			IdcOrg org = IdcOrg.dao.findById(u.getOrgId());
			if (u != null) {
				if (u.getPassword().equals(password)) {// 密码相同
					
					// 设置session
					this.setSessionAttr("SYS_LOGINFLAG", true);
					this.setSessionAttr("SYS_USER", u);
					this.setSessionAttr("SYS_USER_ROLE",role);
					this.setSessionAttr("SYS_USER_ORG",org);
					Map<String,String> authCode = IdcMenuService.queryAuthCode(u.getUserId().toString());
					this.setSessionAttr("SYS_USER_AUTHCODE",authCode);

					this.setAttr("valid", true);
					this.setAttr("msg", "登陆验证成功!");
					this.renderJson();
				} else {
					this.setAttr("valid", false);
					this.setAttr("msg", "用户密码不正确!");
					this.renderJson();
				}
			} else {
				this.setAttr("valid", false);
				this.setAttr("msg", "该用户账号不存在!");
				this.renderJson();
			}
		} else {
			this.setAttr("valid", false);
			this.setAttr("msg", "验证码输入有误!");
			this.renderJson();
		}

	}

	public void code() {
		CaptchaRender img = new CaptchaRender();
		render(img);
	}

	public void logout() {
		this.removeSessionAttr("SYS_LOGINFLAG");
		this.removeSessionAttr("SYS_USER");
		this.removeSessionAttr("SYS_USER_ROLE");
		this.removeSessionAttr("SYS_USER_ORG");
		this.removeSessionAttr("SYS_USER_AUTHCODE");
		this.redirect("/login");
	}

}
